import { Button } from "@/src/components/ui/button";
import prisma from "@/src/db/db";
import { formatCurrency } from "@/src/lib/formatters";
import Image from "next/image";
import Link from "next/link";
import { notFound } from "next/navigation";
import React from "react";
import Stripe from "stripe";
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);

const Success = async ({ searchParams }) => {
  const paymentIntent = await stripe.paymentIntents.retrieve(
    searchParams.payment_intent
  );
  if (!paymentIntent.metadata.productId) {
    return notFound();
  }
  const product = await prisma.product.findUnique({
    where: { id: paymentIntent.metadata.productId },
  });
  if (!product) {
    return notFound();
  }
  const isSuccess = paymentIntent.status === "succeeded";
  return (
    <div className="max-w-5xl w-full mx-auto space-y-8">
      <h1 className="text-4xl font-bold">{isSuccess ? "Success" : "Error"}</h1>
      <div className="flex gap-4 items-center">
        <div className="aspect-video flex-shrink-0 w-1/3 relative">
          <Image
            src={product.imagePath.slice(6)}
            fill
            alt={product.name}
            className="object-cover"
          />
        </div>
        <div>
          <div className="text-lg">{formatCurrency(product.priceInCents)}</div>
          <h1 className="text-2xl font-bold">{product.name}</h1>
          <div className="line-clamp-3 text-muted-foreground">
            {product.description}
          </div>
          <Button asChild className="mt-4" size="lg">
            {isSuccess ? (
              <a
                download
                href={`/api/products/download-verification/${await createDownloadVerificationId(
                  product.id
                )}`}
              >
                下载
              </a>
            ) : (
              <Link href={`/products/${product.id}/purchase`}>Try Again</Link>
            )}
          </Button>
        </div>
      </div>
    </div>
  );
};

async function createDownloadVerificationId(productId) {
  // productid 绑定下载
  const res = await prisma.downloadVerification.create({
    data: { productId, expiresAt: new Date(Date.now() + 1000 * 60 * 60 * 24) },
  });
  return res.id;
}

export default Success;
